package com.bjfu.intelligentrecognizeserver.interceptor;

import com.bjfu.intelligentrecognizeserver.Util.JwtUtil;
import com.bjfu.intelligentrecognizeserver.common.constant.JwtClaimsConstant;
import com.bjfu.intelligentrecognizeserver.context.BaseContext;
import com.bjfu.intelligentrecognizeserver.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
@RequiredArgsConstructor
public class JwtTokenUserInterceptor implements HandlerInterceptor {
    private final JwtProperties jwtProperties;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)) {
            //判断当前拦截到的是Controller的方法还是其他资源
            return true;
        }

        //从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //校验令牌
        try {
            log.info("jwt校验:{}",token);
            Claims claims = JwtUtil.parseJwt(jwtProperties.getUserSecretKey(), token);
            Integer userId = Integer.valueOf(claims.get(JwtClaimsConstant.USER_ID).toString());
            log.info("当前用户id:{}",userId);

            BaseContext.setCurrentId(userId);
            return true;
        }catch (Exception e) {
            log.info(e.getMessage());
            response.setStatus(401);
            return false;
        }

    }
}
